/**
 *    Copyright 2009-2017 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

import javax.sql.DataSource;

import com.hsh.test.Order;
import org.apache.ibatis.builder.BaseBuilder;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.loader.ProxyFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.AutoMappingUnknownColumnBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

/**
 * XMLConfigBuilder是BaseBuilder的子类，它扮演的是具体建造者的角色，主要负责解析mybatis-config.xml配置文件。
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */
public class XMLConfigBuilder extends BaseBuilder {
  /**
   * 标识是否已经解析过mybatis-config.xml配置文件
   */
  private boolean parsed;
  /**
   * mybatis-config.xml配置文件的XPath解析器，提供了一些解析XML的方法。
   */
  private final XPathParser parser;
  /**
   * 标识<environment>配置的名称，默认读取<environment>标签的default属性
   */
  private String environment;
  /**
   * ReflectorFactory负责创建和缓存Reflector对象
   */
  private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

  public XMLConfigBuilder(Reader reader) {
    this(reader, null, null);
  }

  public XMLConfigBuilder(Reader reader, String environment) {
    this(reader, environment, null);
  }

  public XMLConfigBuilder(Reader reader, String environment, Properties props) {
    this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  public XMLConfigBuilder(InputStream inputStream) {
    this(inputStream, null, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment) {
    this(inputStream, environment, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
    this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
    super(new Configuration());
    ErrorContext.instance().resource("SQL Mapper Configuration");
    this.configuration.setVariables(props);
    this.parsed = false;
    this.environment = environment;
    this.parser = parser;
  }
  /**
   * 解析mybatis-config.xml配置文件的入口，返回Configuration对象。
   * 实际由{@link #parseConfiguration(XNode)}方法完成。
   */
  public Configuration parse() {
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }
  /**
   * 真正解析mybatis-config.xml配置文件的方法
   * @param root configuration标签 即整个config.xml文档元素
   */
  @Order(v="2.2", d="解析config.xml文件的各标签,并将XMLConfigBuilder实例转化为Configuration实例")
  private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
    	//解析配置文件中的properties元素
      propertiesElement(root.evalNode("properties"));
      //解析配置文件中的settings元素
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      //如果settings配置中包含了vfsImpl相关配置，则设置configuration的vfsImpl,虚拟文件系统
      loadCustomVfs(settings);
      //解析配置文件中的typeAliases元素
      typeAliasesElement(root.evalNode("typeAliases"));
      //解析配置文件中的plugins元素
      pluginElement(root.evalNode("plugins"));
      /**
       * 解析配置文件中的objectFactory元素。
       * MyBatis 每次创建结果对象的新实例时，它都会使用一个对象工厂（ObjectFactory）实例来完成。 
       * 默认的对象工厂需要做的仅仅是实例化目标类，要么通过默认构造方法，要么在参数映射存在的时候通过参数构造方法来实例化。
       *  如果想覆盖对象工厂的默认行为，则可以通过创建自己的对象工厂来实现
       */
      objectFactoryElement(root.evalNode("objectFactory"));

      //解析配置文件中的objectWrapperFactory元素
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      //解析配置文件中的reflectorFactory元素
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      //把settings的相关配置赋值到Configuration对应的属性中
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      //解析配置文件中的environments元素
      environmentsElement(root.evalNode("environments"));
      /**
       * 解析配置文件中的databaseIdProvider元素
       * 
       * MyBatis 可以根据不同的数据库厂商执行不同的语句，这种多厂商的支持是基于映射语句中的 databaseId 属性。
       *  MyBatis 会加载不带 databaseId 属性和带有匹配当前数据库 databaseId 属性的所有语句。
       *   如果同时找到带有 databaseId 和不带 databaseId 的相同语句，则后者会被舍弃。 
       * 为支持多厂商特性只要像下面这样在 mybatis-config.xml 文件中加入 databaseIdProvider
       */

      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      //解析配置文件中的typeHandlers元素
      typeHandlerElement(root.evalNode("typeHandlers"));
      //解析配置文件中的mappers元素
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }
  /**
   * 解析settings对象，并封装成Properties对象。
   * 	注意：校验了settings是否合法，即{@link #Configuration}中是否存在该属性。
   * @param context settings标签
   * @return 还回settings标签中所有的key-value
   */
  @Order(v="2.2.2", d="解析config.xml中settings元素")
  private Properties settingsAsProperties(XNode context) {
    if (context == null) {
      return new Properties();
    }
    Properties props = context.getChildrenAsProperties();
    // Check that all settings are known to the configuration class
    MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
    for (Object key : props.keySet()) {
      if (!metaConfig.hasSetter(String.valueOf(key))) {
        throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
      }
    }
    return props;
  }
  /**
   * 如果settings配置文件中有vfsImpl相关配置信息，
   * 	设置configuration对象的vfsImpl属性。
   * @param props
   * @throws ClassNotFoundException
   */
  private void loadCustomVfs(Properties props) throws ClassNotFoundException {
    String value = props.getProperty("vfsImpl");
    if (value != null) {
      String[] clazzes = value.split(",");
      for (String clazz : clazzes) {
        if (!clazz.isEmpty()) {
          @SuppressWarnings("unchecked")
          Class<? extends VFS> vfsImpl = (Class<? extends VFS>)Resources.classForName(clazz);
          configuration.setVfsImpl(vfsImpl);
        }
      }
    }
  }
  /**
   * 解析类型别名元素，并注册到TypeAliasRegistry对象中
   * typeAliases标签 可以包含两种子标签 package 和 typeAlias
   * typeAlias 指定类的别名，可以自定义
   * package 指定包下所有的类的别名，可以理解为批量的typeAlias
   * @param parent
   */
  @Order(v="2.2.3", d="解析typeAliases标签, 并将对应映射关系记录/注册到TypeAliasRegistry实例中")
  private void typeAliasesElement(XNode parent) {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
    	  //解析<package name="#"/>类型的子元素
        if ("package".equals(child.getName())) {
          String typeAliasPackage = child.getStringAttribute("name");
          configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
        } else {//解析<typeAlias alias="#" type="#"/>类型的子元素
          String alias = child.getStringAttribute("alias");
          String type = child.getStringAttribute("type");
          try {
            Class<?> clazz = Resources.classForName(type);
            if (alias == null) {
              typeAliasRegistry.registerAlias(clazz);
            } else {
              typeAliasRegistry.registerAlias(alias, clazz);
            }
          } catch (ClassNotFoundException e) {
            throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
          }
        }
      }
    }
  }
  /**
   * 解析配置文件中的插件（plugin），并注册到interceptor中
   * @param parent plugins标签
   * @throws Exception
   */
  @Order(v="2.2.4", d="解析plugins标签, 并将解析到的plugin保存到Configuration实例中")
  private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        String interceptor = child.getStringAttribute("interceptor");
        Properties properties = child.getChildrenAsProperties();
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
        interceptorInstance.setProperties(properties);
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }
  /**
   * 解析对象功能，并赋值到configuration的属性中
   * @param context
   * @throws Exception
   */
  @Order(v="2.2.5", d="解析objectFactory标签,只能同时有一个objectFactory元素 并将解析到的objectFactory保存到Configuration实例中")
  private void objectFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties properties = context.getChildrenAsProperties();
      ObjectFactory factory = (ObjectFactory) resolveClass(type).newInstance();
      factory.setProperties(properties);
      configuration.setObjectFactory(factory);
    }
  }
  /**
   * 解析配置文件中的objectWrapperFactory元素
   * @param context
   * @throws Exception
   */
  @Order(v="2.2.6", d="解析objectWrapperFactory标签")
  private void objectWrapperFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).newInstance();
      configuration.setObjectWrapperFactory(factory);
    }
  }
  /**
   * 解析配置文件中的reflectorFactory元素
   * @param context
   * @throws Exception
   */
  @Order(v="2.2.7", d="解析reflectorFactory标签, 并将其置于Configuration实例中")
  private void reflectorFactoryElement(XNode context) throws Exception {
    if (context != null) {
       String type = context.getStringAttribute("type");
       ReflectorFactory factory = (ReflectorFactory) resolveClass(type).newInstance();
       configuration.setReflectorFactory(factory);
    }
  }
  /**
   * 解析properties元素
   * @param context 代表了properties节点
   * @throws Exception
   */
  @Order(v="2.2.1", d="解析config.xml中properties元素")
  private void propertiesElement(XNode context) throws Exception {
    if (context != null) {
      @Order(v="2.2.1.1", d="解析properties中propertie元素的name和value并生成Map")
      Properties defaults = context.getChildrenAsProperties();

      @Order(v="2.2.1.2", d="解析properties标签中url/resource,获取较高优先级的外部配置")
      // properties 元素中的 resource 属性读取类路径下属性文件，并覆盖已读取的同名属性
      String resource = context.getStringAttribute("resource");
      // properties 元素中的 url 属性指定的路径读取属性文件，并覆盖已读取的同名属性(Http链接)
      String url = context.getStringAttribute("url");
      if (resource != null && url != null) {//resource 和 url 只能够配置其中一个，否则抛出异常。
        throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
      }
      //properties元素体内指定的属性会被配置文件中同名属性覆盖
      if (resource != null) {
        defaults.putAll(Resources.getResourceAsProperties(resource));
      } else if (url != null) {
        defaults.putAll(Resources.getUrlAsProperties(url));
      }
      @Order(v="2.2.1.3", d="配置文件按照优先级进行覆盖,并将配置回置到XMLConfigBuilder.configuration中")
      //方法参数传递的属性，覆盖已读取的同名属性
      Properties vars = configuration.getVariables();
      if (vars != null) {
        defaults.putAll(vars);
      }
      //解析器，属性值配置
      parser.setVariables(defaults);
      //configuration对象的属性值赋值
      configuration.setVariables(defaults);
    }
  }

  @Order(v="2.2.8", d="将解析到的settings的内容反馈到各对象实例中")
  private void settingsElement(Properties props) throws Exception {
	//指定 MyBatis应如何自动映射列到字段或属性。 NONE 表示取消自动映射；PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集（无论是否嵌套）。
    configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
    //指定发现自动映射目标未知列（或者未知属性类型）的行为。
    //NONE: 不做任何反应
    //WARNING: 输出提醒日志 ('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' 的日志等级必须设置为 WARN)
    //FAILING: 映射失败 (抛出 SqlSessionException)
    configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
    //全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存。
    configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
    //指定 Mybatis 创建具有延迟加载能力的对象所用到的代理工具。	CGLIB | JAVASSIST
    configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
    configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
    configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
    configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
    configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
    configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
    configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
    configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
    configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
    configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
    configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
    configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
    configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
    configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
    configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
    configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
    //配置默认的枚举类型处理器
    @SuppressWarnings("unchecked")
    Class<? extends TypeHandler> typeHandler = (Class<? extends TypeHandler>)resolveClass(props.getProperty("defaultEnumTypeHandler"));
    configuration.setDefaultEnumTypeHandler(typeHandler);
    //指定当结果集中值为 null 的时候是否调用映射对象的 setter（map 对象时为 put）方法，这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。注意基本类型（int、boolean等）是不能设置成 null 的。
    configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
    //允许使用方法签名中的名称作为语句参数名称。 为了使用该特性，你的工程必须采用Java 8编译，并且加上-parameters选项。（从3.4.1开始）
    configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
    //当返回行的所有列都是空时，MyBatis默认返回null。 当开启这个设置时，MyBatis会返回一个空实例。 请注意，它也适用于嵌套的结果集 (i.e. collectioin and association)。（从3.4.2开始）
    configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
    //指定 MyBatis 增加到日志名称的前缀。
    configuration.setLogPrefix(props.getProperty("logPrefix"));
    //配置mybatis使用的日志实现类
    @SuppressWarnings("unchecked")
    Class<? extends Log> logImpl = (Class<? extends Log>)resolveClass(props.getProperty("logImpl"));
    configuration.setLogImpl(logImpl);
    /**
     * Configuration factory class.
     * Used to create Configuration for loading deserialized unread properties.
     */
    configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
  }
  /**
   * 解析配置文件中的environments元素
   * @param context environments标签
   * @throws Exception
   */
  @Order(v="2.2.8", d="解析environments元素,取出对应/默认的环境配置，并将其置于Configuration实例中")
  private void environmentsElement(XNode context) throws Exception {
    if (context != null) {
      if (environment == null) {
        environment = context.getStringAttribute("default");
      }
      for (XNode child : context.getChildren()) {//解析environment元素
        String id = child.getStringAttribute("id");
        if (isSpecifiedEnvironment(id)) {//判断是否是默认配置，即environments元素的default属性值。比如：<environments default="development">
          //解析事务管理器
          TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
          //解析数据源
          DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
          DataSource dataSource = dsFactory.getDataSource();
          //构建environment对象
          Environment.Builder environmentBuilder = new Environment.Builder(id)
              .transactionFactory(txFactory)
              .dataSource(dataSource);
          //赋值到configuration的对应属性中
          configuration.setEnvironment(environmentBuilder.build());
        }
      }
    }
  }
  /**
   * 解析配置文件中的databaseIdProvider元素
   * @param context
   * @throws Exception
   */
  @Order(v="2.2.9", d="解析databaseIdProvider元素")
  private void databaseIdProviderElement(XNode context) throws Exception {
    DatabaseIdProvider databaseIdProvider = null;
    if (context != null) {
      String type = context.getStringAttribute("type");
      // awful patch to keep backward compatibility
      if ("VENDOR".equals(type)) {
          type = "DB_VENDOR";
      }
      Properties properties = context.getChildrenAsProperties();
      databaseIdProvider = (DatabaseIdProvider) resolveClass(type).newInstance();
      databaseIdProvider.setProperties(properties);
    }
    Environment environment = configuration.getEnvironment();
    if (environment != null && databaseIdProvider != null) {
      String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
      configuration.setDatabaseId(databaseId);
    }
  }
  /**
   * 解析事务管理器对象
   * @param context
   * @return
   * @throws Exception
   */
  private TransactionFactory transactionManagerElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      TransactionFactory factory = (TransactionFactory) resolveClass(type).newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a TransactionFactory.");
  }
  /**
   * 解析数据源元素
   * @param context
   * @return
   * @throws Exception
   */
  private DataSourceFactory dataSourceElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      DataSourceFactory factory = (DataSourceFactory) resolveClass(type).newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a DataSourceFactory.");
  }
  /**
   * 类型处理器元素解析
   * @param parent
   * @throws Exception
   */
  @Order(v="2.2.9", d="解析typeHandlers元素,并将其注册到typeHandlerRegistry中")
  private void typeHandlerElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          String typeHandlerPackage = child.getStringAttribute("name");
          typeHandlerRegistry.register(typeHandlerPackage);
        } else {
          String javaTypeName = child.getStringAttribute("javaType");
          String jdbcTypeName = child.getStringAttribute("jdbcType");
          String handlerTypeName = child.getStringAttribute("handler");
          Class<?> javaTypeClass = resolveClass(javaTypeName);
          JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
          Class<?> typeHandlerClass = resolveClass(handlerTypeName);
          if (javaTypeClass != null) {
            if (jdbcType == null) {
              typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
            } else {
              typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
            }
          } else {
            typeHandlerRegistry.register(typeHandlerClass);
          }
        }
      }
    }
  }
  /**
   * 解析配置文件中的mappers元素
   * @param parent mappers元素
   * @throws Exception
   */
  @Order(v="2.2.10", d="解析mappers元素,并将所有Mapper注册到configuration.mapperRegistry实例中")
  private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {//解析<package>元素
          @Order(v="2.2.10.1", d="如果配置的是package标签,将对应包下所有的类注册成Mapper")
          String mapperPackage = child.getStringAttribute("name");
          configuration.addMappers(mapperPackage);
        } else {//解析<mapper>元素
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            InputStream inputStream = Resources.getResourceAsStream(resource);
            @Order(v="2.2.10.2", d="如果配置的是resource标签,则对应的资源以流的形式读取，并注册成Mapper")
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url != null && mapperClass == null) {
            ErrorContext.instance().resource(url);
            @Order(v="2.2.10.3", d="如果配置的是url标签,则对应的资源以流的形式读取，并注册成Mapper")
            InputStream inputStream = Resources.getUrlAsStream(url);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url == null && mapperClass != null) {
            @Order(v="2.2.10.3", d="如果配置的是class标签,则将对应的类注册成Mapper")
            Class<?> mapperInterface = Resources.classForName(mapperClass);
            configuration.addMapper(mapperInterface);
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          } 
        }
      }
    }
  }

  private boolean isSpecifiedEnvironment(String id) {
    if (environment == null) {
      throw new BuilderException("No environment specified.");
    } else if (id == null) {
      throw new BuilderException("Environment requires an id attribute.");
    } else if (environment.equals(id)) {
      return true;
    }
    return false;
  }

}
